var form;
var layer;
var core_lat="113.571365";
var core_lon="34.823466";
var map = new BMap.Map("allmap");
var opts = {
    height:120,     // 信息窗口高度
};
//页面初始化时加载Layui框架
layui.use(['form', 'layer', 'laydate'], function () {
    form = layui.form;
    layer = layui.layer;

    initArea();
    var areaId = $("#areaId").val();
    if (areaId == "" || areaId == "-1") {
        $("#eqId").attr("disabled", true);
        $("#eqId").css("background-color", "gray");
    }
    //layui的change事件
    form.on('select(changeArea)', function () {
        var areaId = $("#areaId").val();
        if (areaId != -1 && areaId != "") {
            $("#eqId").attr("disabled", false);
            $("#eqId").css("background-color", "");
            initEq(areaId);
        } else {
            $("#eqId").empty();
            $("#eqId").append("<option value=''>请选择设备</option>");
            $("#eqId").append("<option value='-1'>全部</option>");
            $("#eqId").attr("disabled", true);
            $("#eqId").css("background-color", "gray");
        }
        form.render();
    });

    // 查询
    $("#search").click(function () {
        initEqMap(); //要触发的方法
        return false;
    });

    //回车事件
    $(document).keydown(function (event) {
        var code = event.which;
        if (code == 13) {
            initEqMap(); //要触发的方法
        }
    });



});

function closeInfo(){
    $("#info").hide();
}
/**
 * 初始化区域
 */
function initArea() {
    $.ajax({
        url: basePath + "/area/findAllArea.do",
        type: "post",
        data:{equType: 0 ,equModel : 0  },
        dataType: "html",
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            if (jsonData.length > 0) {
                $("#areaId").empty();
                if (jsonData.length == 1) {
                    $("#areaId").append("<option value='" + jsonData[0].id + "'>" + jsonData[0].areaName + "</option>");
                    $("#areaIdtemp").val(jsonData[0].id);
                    $("#eqId").attr("disabled", false);
                    $("#eqId").css("background-color", "");
                    initEq(jsonData[0].id);
                } else if (jsonData.length > 1) {
                    $("#areaId").append("<option value=''>请选择区域</option>");
                    $("#areaId").append("<option value='-1'>全部</option>");
                    for (var i = 0; i < jsonData.length; i++) {
                        $("#areaId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].areaName + "</option>");
                    }
                }
            } else {
                $("#areaId").append("<option value=''>请选择区域</option>");
            }
            initEqMap() ;
            form.render();
        }
    });
}

/**
 * 初始化设备
 */
function initEq(areaId) {
    $.ajax({
        url: basePath + "equipment/getEqByAreaId.action?areaId=" + areaId,
        type: "post",
        dataType: "html",
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            $("#eqId").empty();
            if (jsonData.length > 0) {
                if (jsonData.length == 1) {
                    $("#eqId").append("<option value='" + jsonData[0].id + "'>" + jsonData[0].name + "</option>");
                } else if (jsonData.length > 1) {
                    $("#eqId").append("<option value=''>请选择设备</option>");
                    $("#eqId").append("<option value='-1'>全部</option>");
                    for (var i = 0; i < jsonData.length; i++) {
                        $("#eqId").append("<option value='" + jsonData[i].id + "'>" + jsonData[i].name + "</option>");
                    }
                }
            } else {
                $("#eqId").append("<option value=''>请选择设备</option>");
            }
            form.render();
        }
    });
}

/**
 * 获取设备地图
 */
function initEqMap() {
    var equId =  window.localStorage.getItem("equ_ins_Id");
    window.localStorage.removeItem("equ_ins_Id");

    // 百度地图API功能
    map = new BMap.Map("allmap");
    map.addControl(new BMap.MapTypeControl());   //添加地图类型控件
    map.enableScrollWheelZoom(true);
    map.clearOverlays();


    if(equId == null){
        intMap();
    }  else{
        initInsMap(equId);
    }

}

function intMap(){
    var areaId = $("#areaId").val();
    var eqId = $("#eqId").val();
    var paramData = {
        "equipment.id": eqId,
        "equipment.areaId": areaId
    };
    $.ajax({
        url: basePath + "/equipment/findEquipmentMap.do",
        type: "post",
        data: paramData,
        dataType: "html",
        success: function (data) {
            var jsonData = eval("(" + data + ")");
            if (jsonData.length > 0) {
                var infoMap = "";//内容
                var title =  "" ;//标题
                if(jsonData.length==1){
                    core_lat = jsonData[0].lat ;
                    core_lon =jsonData[0].lon ;
                }
                var isFor = true ;
                for (var i = 0,j=0; i < jsonData.length; i++) {
                    var eq_lat = jsonData[i].lat;
                    var eq_lon = jsonData[i].lon;
                    if(eq_lon>eq_lat){
                        var eqAdd = eq_lat;
                        eq_lat =eq_lon ;
                        eq_lon =eqAdd
                    }

                    var eqType = jsonData[i].eqType;//设备类型
                    var eqStuats = jsonData[i].status ;
                    var icon = null;

                    if (eqType == 1) {
                        icon = basePath + "images/bug.png";
                        infoMap = "虫情监测设备" + jsonData[i].name;

                    } else if (eqType == 2) {
                        icon = basePath + "images/seeding.png";
                        title = "苗情监测设备" ;
                        infoMap = jsonData[i].name;

                    } else if (eqType == 3) {
                        icon = basePath + "images/meteor.png";
                        title = "气象墒情监测设备" ;
                        infoMap = jsonData[i].name;

                    } else if (eqType == 4) {
                        title = "灾情监测设备" ;
                        icon = basePath + "images/disaster.png";
                        infoMap = jsonData[i].name;

                    } else if (eqType == 5) {
                        title = "孢子监测设备" ;
                        icon = basePath + "images/illness.png";
                        infoMap = jsonData[i].name;
                    }else if (eqType == 6) {
                        if(eqStuats == 1){
                            icon = basePath + "images/insno.png";
                        }
                        if(eqStuats == 0){
                            icon = basePath + "images/insyes.png";
                        }
                        title = "自动杀虫设备" ;
                        infoMap = jsonData[i].name;
                    }

                    var myIcon = new BMap.Icon(icon, new BMap.Size(25, 33));
                    var mkr = new BMap.Marker(new BMap.Point(eq_lat,eq_lon), {icon: myIcon});

                    if(isFor){
                        if(eq_lat>73&&eq_lat<136&&eq_lon>3&&eq_lon<53){
                            core_lat = eq_lat ;
                            core_lon = eq_lon ;
                            isFor = false ;
                        }
                    }


                    map.addOverlay(mkr);
                    // var contents = title + "\r\n" + infoMap ;
                    var contents = "<table  border=\"1\" bordercolor=\"#E2E2E2\" style=\"border-collapse:collapse;\">" +
                        "</td></tr><tr><td class=\"td1\">编号</td><td class=\"td2\">"+
                        jsonData[i].code +
                        "<tr><td class=\"td1\">名称</td><td class=\"td2\">" +
                        infoMap +
                        "</td></tr><tr><td class=\"td1\">型号</td><td class=\"td2\">"+
                        title +
                        "</td></tr><tr><td class=\"td1\">状态</td><td class=\"td2\">"+
                        (eqStuats == 1  ? "<font color=\"#FF6838\">离线</font>":"<font color=\"#1AA094\">在线</font>" )+
                        "</td></tr></table>";

                    // addClickHandler(contents,mkr);
                    addClickHandler2(jsonData[i],mkr);
                }
            }

            if(core_lat == "116.41885045745359"  ||  core_lat == "91.20135"){
                core_lat ="113.571365";
            }
            if (core_lon == "39.91601770983428"  || core_lon == "29.93426"  ) {
                core_lon="34.823466";
            }


            if (findLoginInfo() == "cqqny" ){
                map.centerAndZoom(new BMap.Point(core_lat,core_lon), 11);
                var bdary = new BMap.Boundary();
                bdary.get("济南市长清区", function(rs){       //获取行政区域
                    var count = rs.boundaries.length; //行政区域的点有多少个
                    if (count === 0) {
                        alert('未能获取当前输入行政区域');
                        return ;
                    }
                    var pointArray = [];
                    for (var i = 0; i < count; i++) {
                        var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多边形覆盖物
                        map.addOverlay(ply);  //添加覆盖物
                    }

                });
            }else{
                map.centerAndZoom(new BMap.Point(core_lat,core_lon), 16);
            }

        }
    });
}

function initInsMap(equId) {
    $.post(basePath + "insecticidal/getInsecticidalById.action", "id=" + equId, function (data) {
        var ins = data.aaData
        var eqStuats = ins.insStatus ;
        var icon = null;

        if(eqStuats == 0){
            icon = basePath + "images/insno.png";
        }
        if(eqStuats != 0){
            icon = basePath + "images/insyes.png";
        }
        var info = "自动杀虫设备：" + ins.insName;

        var eq_lat = ins.insLat;
        var eq_lon = ins.insLon;


        var pt = new BMap.Point(eq_lon, eq_lat);
        var myIcon = new BMap.Icon(icon, new BMap.Size(25,33));
        var marker = new BMap.Marker(pt,{icon:myIcon});  // 创建标注
        map.addOverlay(marker);

        var point =new BMap.Point(eq_lon,eq_lat);
        map.centerAndZoom(point, 16);
        map.addOverlay(marker);               // 将标注添加到地图中
        marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画

        var contents = "<table  border=\"1\" bordercolor=\"#E2E2E2\" style=\"border-collapse:collapse;\">" +
            "</td></tr><tr><td class=\"td1\">编号</td><td class=\"td2\">"+
            equId +
            "<tr><td class=\"td1\">名称</td><td class=\"td2\">" +
            ins.insName +
            "</td></tr><tr><td class=\"td1\">型号</td><td class=\"td2\">"+
            "自动杀虫灯设备" +
            "</td></tr><tr><td class=\"td1\">状态</td><td class=\"td2\">"+
            (eqStuats == 0  ? "<font color=\"#FF6838\">离线</font>":"<font color=\"#1AA094\">在线</font>" )+
            "</td></tr></table>";

        var infoWindow = new BMap.InfoWindow(contents, opts);  // 创建信息窗口对象
        map.openInfoWindow(infoWindow,point);

        equId = null ;
    }, "json")

}

function addClickHandler(content,marker){
    marker.addEventListener("click",function(e){
        openInfo(content,e)}
    );
}


function openInfo(content,e){
    var p = e.target;
    var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
    var infoWindow = new BMap.InfoWindow(content,opts);  // 创建信息窗口对象
    map.openInfoWindow(infoWindow,point); //开启信息窗口
}

function addClickHandler2(obj,marker){
    marker.addEventListener("click",function(e){
            $("#info").hide();
            $("#info").height("126px");
            var title = "";
            var eqType = obj.eqType ;
            if (eqType == 1)title = "虫情设备"
            else if (eqType == 2)title = "苗情监测设备" ;
            else if (eqType == 3)title = "气象墒情监测设备" ;
            else if (eqType == 4)title = "灾情监测设备" ;
            else if (eqType == 5) title = "孢子监测设备" ;
            else if (eqType == 6) title = "自动杀虫设备" ;


            $("#info_table").empty();
            var html = "" ;

            var html = "<tr> <td class=\"td0\"><span>编号</span></td><td class=\"td1\"><span>" + obj.code + "</span></td> </tr>" ;
            html += "<tr> <td class=\"td0\"><span>名称</span></td><td class=\"td1\"><span>" + obj.name + "</span></td> </tr>" ;
            html += "<tr> <td class=\"td0\"><span>型号</span></td><td class=\"td1\"><span>" + title + "</span></td> </tr>" ;
            // html += "<tr> <td class=\"td0\"><span>状态</span></td><td class=\"td1\"><span>" + (obj.status == 1 ? "<font color=\"#FF6838\">离线</font>":"<font color=\"#1AA094\">在线</font>" ) + "</span></td> </tr>" ;


            if (eqType == 3){
                var paramData = {
                    "equipmentId": obj.id
                };
                $.ajax({
                    url: basePath + "monitor/getEnvitByMap.action",
                    type: "post",
                    data: paramData,
                    dataType: "html",
                    success: function (data) {

                        if (data.length > 5){
                            var jsonData = eval("(" + data + ")");
                            var da = jsonData.data ;
                            var h =130+ (da.length+2)*30;
                            // var h = 130+ (da.length+2)*30;
                            h += "px"
                            $("#info").height(h);
                            if (jsonData.data.length > 0){
                                // html += "<tr ><th colspan=\"2\"><hr style=\"width: 100%;background-color: #9BB978;border: none;height: 2px;\"></th></tr><tr> <td class=\"td0\"><span>采集时间</span></td><td class=\"td1\"><span>"
                                html += "<tr><td class=\"td0\"><span>采集时间</span></td><td class=\"td1\"><span>"+ jsonData.collecTime.slice(0,19) + "</span></td> </tr>";

                                for (var i = 0 ; i <da.length ; i++){
                                    var sendName = da[i].name ;
                                    if (sendName.indexOf("风速") !== -1){
                                        var num = da[i].value * 1 ;
                                        html += "<tr> <td class=\"td0\"><span>风力</span></td><td class=\"td1\"><span>" + windPower(num)+ "</span></td> </tr>";
                                    }else if(sendName.indexOf("风向") !== -1){
                                        var num = da[i].value * 1 ;
                                        html += "<tr> <td class=\"td0\"><span>风向</span></td><td class=\"td1\"><span>" + oc2direction(num) + "</span></td> </tr>";
                                    }else{
                                        html += "<tr> <td class=\"td0\"><span>"+da[i].name+"</span></td><td class=\"td1\"><span>" + da[i].value +"" + getUnit(da[i].name)+ "</span></td> </tr>";
                                    }

                                }

                            }
                        }
                        $("#info_table").html(html);

                    }
                });
            }else{
                $("#info_table").html(html);
            }
            $("#info").show();
        }
    );

}

function getUnit(sendName){
    var unit = "" ;
    if(sendName.indexOf("风向") !== -1){
        unit = "&deg;";
    }
    if(sendName.indexOf("风速") !== -1){
        unit = "m/s";
    }
    if(sendName.indexOf("露点") !== -1){
        unit = "&deg;C";
    }
    if(sendName.indexOf("雨雪") !== -1){
        unit = "";
    }
    if(sendName.indexOf("雨量") !== -1){
        unit = "mm";
    }
    if(sendName.indexOf("蒸发量") !== -1){
        unit = "mm";
    }
    if(sendName.indexOf("盐分") !== -1){
        unit = "ms/cm<sup>3</sup>";
    }
    if(sendName.indexOf("湿度") !== -1){
        unit = "%";
    }
    if(sendName.indexOf("氨气") !== -1){
        unit = "g/L";
    }
    if(sendName.indexOf("气压") !== -1){
        unit = "hPa";
    }
    if(sendName.indexOf("光照") !== -1){
        unit = "lux";
    }
    if(sendName.indexOf("日照") !== -1){
        unit = "h";
    }
    if(sendName.indexOf("温度") !== -1 || sendName.indexOf("土温")!== -1){
        unit = "&deg;C";
    }

    if(sendName.indexOf("光合") !== -1){
        unit = "umol";
    }
    if(sendName.indexOf("PM") !== -1){
        unit = "&micro;g/m<sup>3</sup>";
    }
    if(sendName.indexOf("PH") !== -1){
        unit = "";
    }
    if(sendName.indexOf("Co2") !== -1){

        unit = "ppm";
    }
    if(sendName.indexOf("土壤水分") !== -1 || sendName.indexOf("土湿")!== -1){
        unit = "%";
    }

    return unit ;
}

//风向度数转方向
function oc2direction(num) {
    var value = "数据未上传！" ;

    if ((num >=337.5 && num<360)||(num >=0 && num<22.5))
        value = "北风" ;
    if (num >=22.5 && num<67.5)
        value = "东北风" ;
    if (num >=67.5 && num<112.5)
        value = "东风" ;
    if (num >=112.5 && num<157.5)
        value = "东南风" ;
    if (num >=157.5 && num<202.5)
        value = "南风" ;
    if (num >=202.5 && num<247.5)
        value = "西南风" ;
    if (num >=247.5 && num<292.5)
        value = "西风" ;
    if (num >=292.5 && num<337.5)
        value = "西北风" ;

    return value ;
}

//风力转换
function windPower(num){
    var value = "数据未上传！" ;

    if (num >=0 && num<0.3)
        value = "无风" ;
    if (num >=0.3 && num<1.6)
        value = "1级风" ;
    if (num >=1.6 && num<3.4)
        value = "2级风" ;
    if (num >=3.4 && num<5.5)
        value = "3级风" ;
    if (num >=5.5 && num<8.0)
        value = "4级风" ;
    if (num >=8.0 && num<10.8)
        value = "5级风" ;
    if (num >=10.8 && num<13.9)
        value = "6级风" ;
    if (num >=13.9 && num<17.2)
        value = "7级风" ;
    if (num >=17.2 && num<20.5)
        value = "8级风" ;
    if (num >=20.8 && num<24.5)
        value = "9级风" ;
    if (num >=24.5 && num<28.5)
        value = "10级风" ;
    if (num >=28.5 && num<32.7)
        value = "11级风" ;
    if (num >=32.7 && num<37.0)
        value = "12级风" ;
    if (num >=37.0 && num<41.5)
        value = "13级风" ;
    if (num >=41.5 && num<46.2)
        value = "14级风" ;
    if (num >=46.2 && num<51.0)
        value = "15级风" ;
    if (num >=51.0 && num<56.1)
        value = "16级风" ;
    if (num >=56.1 && num<61.3)
        value = "17级风" ;
    if (num >=61.3 )
        value = "17级以上" ;

    return value ;
}


//查询登录人信息
function  findLoginInfo(){
    var  loginName="";
    $.ajax({
        url: basePath + "/user/selectUserInfo.do",
        type: "post",
        dataType: "html",
        async:false,
        success: function (json){
            var jsonData = eval("(" + json + ")");
            loginName = jsonData.loginName;
            shanDongAreaId =jsonData.shanDongAreaId;
        }
    })
    return loginName
}